<template>
	<el-dialog
		:title="dialog.title[dialog.action]"
		v-model="dialog.visible"
		:width="700"
		height="2000px;"
		:loading="dialog.loading"
		@closed="closed"
	>
		<el-form
			:model="form"
			:rules="rules"
			ref="dialogForm"
			label-width="80px"
			label-position="right"
		>
			<el-form-item label="角色名称" prop="name">
				<el-input v-model="form.name" placeholder="请输入角色名称" clearable :maxlength="50" show-word-limit></el-input>
			</el-form-item>
			<el-form-item label="状态" prop="status">
				<el-switch v-model="form.status" active-text="启用" inactive-text="禁用" />
			</el-form-item>
			<el-form-item label="权限" prop="permissions">
				<permission v-model="form.permissions"></permission>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="dialog.visible = false" >关闭</el-button>
			<el-button type="primary" :loading="dialog.saving" @click="submit()">保存</el-button>
		</template>
	</el-dialog>
</template>
<script>
import permission from './permission.vue'
export default {
	components: {
        permission,
    },
	props: {
		modelValue: { type: Boolean, default: () => false },
	},
	data() {
		return {
			/**
             * 弹框页面数据
             */
            dialog: {
                action: 'add',
                title: {
                    add: '新增角色',
                    edit: '编辑角色',
                },
                visible: false,
                loading: false,
                saving: false,
            },
			/**
			 * 表单数据
			 */
			form: this.getDefaultFormData(),
			/**
			 * 验证规则
			 */
			rules: {
                name: [
                    { required: true, message: '请输入角色名称'}
                ]
            },
			/**
			 * 角色信息
			 */
			role: {
				permissions: []
			}
		}
	},
	methods: {
		/**
		 * 初始化表单
		 */
		open(id = null) {
			this.dialog.visible = true
			this.$nextTick(() => {
				if (!id) {
					this.dialog.action = 'add'
					this.dialog.loading = 'start'
					this.getPermission().then(res => {
						this.form.permissions = res.data
						this.dialog.loading = 'end'
					}).catch(() => {
						this.dialog.loading = 'wait'
					})
				} else {
					this.dialog.action = 'edit'
					this.dialog.loading = 'start'
					this.setData(id).then(res => {
						this.dialog.loading = 'end'
					}).catch(() => {
						this.dialog.loading = 'wait'
					})
				}
			})

		},
		/**
		 * 表单提交
		 */
		submit() {
			this.$refs.dialogForm.validate((valid) => {
				if (!valid) {
					return
				}

				this.dialog.saving = true
				let request = null
				const form = {
					name: this.form.name,
					status: this.form.status ? 1 : 0,
					permissions: []
				}
				this.getCheckedKeys(this.form.permissions, form.permissions)

				if (this.dialog.action == 'add') {
					request = this.$API.system.role.action.post(form)
				} else {
					form.id = this.role.id
					request = this.$API.system.role.action.put(form)
				}

				request.then(() => {
					this.dialog.saving = false
					this.dialog.visible = false
					this.$message.success("保存成功")
					this.$emit('success')
				}).catch(() => {
					this.dialog.saving = false
				})
			})
		},
		/**
		 * 获取选中的权限
		 */
		getCheckedKeys(permissions, fromPermissions) {
			permissions.forEach(item=>{
				if(item.children){
					this.getCheckedKeys(item.children, fromPermissions)
				} else {
					item.permission.forEach(_item => {
						if(_item.checked){
							fromPermissions.push(_item.key)
						}
					})
				}
			})
		},
		/**
         * 设置数据
         */
        setData(id) {
            return new Promise((resolve, reject) => {
                this.$API.system.role.action.get({id: id}).then(res => {
                    const form = {
                        id: res.data.id,
                        name: res.data.name,
                        status: res.data.status.value ? true : false,
                        permissions: res.data.permission
                    }
                    this.form = form
                    this.role = res.data
                    resolve(res.data)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        /**
         * 重置表单数据
         */
        resetForm() {
            this.form = this.getDefaultFormData()
			this.role = this.getDefaultRoleData()
        },
        /**
         * 获取默认的变动数据
         */
        getDefaultFormData () {
            return {
				name: '',
				status: true,
				permissions: []
			}
        },
		/**
         * 获取默认管理员数据
         */
        getDefaultRoleData() {
            return {
                permissions: []
            }
        },
		/**
		 * 获取权限
		 */
		getPermission() {
			return this.$API.system.permission.tree.get()
		},
		/**
		 * 关闭后的事件处理
		 */
		closed() {
			//重置表单数据
			this.resetForm()
			//重置表单验证
			if (this.$refs['dialogForm'] && this.$refs['dialogForm'].resetFields) {
				this.$refs['dialogForm'].resetFields()
			}
		}
	}
}
</script>
